package com.example.stroebackstage.dao;

import com.example.stroebackstage.utils.LinkMySQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

public class CategoryDao {
    //    增
    public static boolean insertCategory(String name){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int numb = 0;
        try {
            conn = LinkMySQL.getConnection();
            String sql = "insert into commoditytype(type_name)values(?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,name);
            numb = pstmt.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(pstmt,conn);
        }
        return numb>0;
    }
    //    删
    public static boolean delCategory(int id){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int numb = 0;
        try {
            conn = LinkMySQL.getConnection();
            String sql =
                    "delete from commoditytype where type_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,id);
            numb = pstmt.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(pstmt,conn);
        }
        return numb>0;
    }
    //    改
    public static boolean updateCategory(int id,String name){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int numb = 0;
        try {
            conn = LinkMySQL.getConnection();
            String sql =
                    "update commoditytype set type_name = ?  where type_id=?" ;
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,name);
            pstmt.setInt(2,id);
            numb = pstmt.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            LinkMySQL.release(pstmt,conn);
        }
        return numb>0;
    }
    //    查
    public static HashMap<Integer,String> selectCategory(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        HashMap<Integer,String> hashMap = new HashMap<>();
        try {
            conn = LinkMySQL.getConnection();
            String sql = "select * from commoditytype ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                hashMap.put(rs.getInt("type_id"),rs.getString("type_name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            LinkMySQL.release(rs,pstmt,conn);
        }
        return hashMap;
    }
}
